#ifndef CHINACTPTRADERTHREAD_H
#define CHINACTPTRADERTHREAD_H

#include <QThread>
#include <QObject>
#include "chinactptrader.h"
class ChinaCtpTraderThread: public QThread {
    Q_OBJECT

public:
    explicit ChinaCtpTraderThread(QObject *parent = nullptr);
    ~ChinaCtpTraderThread() override;

    // 启动行情服务
    void startMd(const QString &frontAddr,const QString brokerID = "",const QString inventorID = "",const QString password = "",const QString appID = "",const QString authCode = "");

    // 停止行情服务
    void stopMd();

    // 获取下单流水好
    QString getOrderRef();

    // 开仓
    void openBuyOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice);
    // 开仓
    void openSellOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice);

    // 平仓
    void closeBuyOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice,const bool isTodayOrder);

    // 平仓
    void closeSellOrder(const QString exchange,const QString symbol,const int quatity,const double openPrice,const bool isTodayOrder);

    // 撤单
    void revokeOrder(const QString symbol,const QString orderID);

    // 查询持仓
    void reqPosition();

    // 查询持仓明细
    void reqPositionDetail();

    // 查询今日成交
    void reqTraderByToday();

    // 查询今日资金流水
    void reqTranferByToday();

    // 查询今日资金流水
    void reqAccountData();

signals:
    // 转发 MdSpi 的信号到主线程
    void connected();
    void disconnected(int reason);
    void loginResult(bool success, const QString &msg);
    void tradeDataReceived(const QString &instrumentID, double lastPrice, double askPrice, double bidPrice);

protected:
    void run() override;  // 线程入口
    int orderRefID = 0;

private:
    CThostFtdcTraderApi *m_mdApi = nullptr;
    ChinaCtpTrader *m_mdSpi = nullptr;
    QString m_frontAddr;  // 交易前置地址
    bool m_running = false;
    QString mBrokerID = "";
    QString mInventorID = "";
    QString mPassword = "";
    QString mAppID = "";
    QString mAuthCode = "";
};

#endif // CHINACTPTRADERTHREAD_H
